//
//  Huati_guangchang_xiangqing_tuijian_vc.m
//  ainkjj
//
//  Created by MAX on 2020/4/30.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Huati_guangchang_xiangqing_tuijian_vc.h"

static NSString * const kCellIdentifier = @"Huati_guangchang_xiangqing_tv_cell";
static NSString * const k_ad_CellIdentifier = @"Topic_getTopicList_tv_ad_cell";




#import "Tiezi_xiangqing_vc.h"

#import "Topic_getTopicList.h"

#import "Huati_guangchang_xiangqing_tv_cell.h"
#import "Topic_getTopicList_tv_ad_cell.h"
#import "Huati_guangchang_xiangqing_vc.h"

@interface Huati_guangchang_xiangqing_tuijian_vc ()<UITableViewDelegate, UITableViewDataSource>
//@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, assign)int refreshIndex;
@property (nonatomic, assign)NSInteger totalPage;
@end

@implementation Huati_guangchang_xiangqing_tuijian_vc


- (void)initTableView {
    [super initTableView];
    // 为了展示效果，这里主动把 estimatedRowHeight 关闭，以与 QMUICellHeightKeyCache 区分开，如果你的 tableView 使用了 estimatedRowHeight，请使用 QMUICellHeightKeyCache，用法参考 QDCellHeightKeyCacheViewController
    
    self.tableView.estimatedRowHeight = 0;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    // tableView.separatorColor = UIColor.redColor;
    //tableView.rowHeight = 96;
    //    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    self.tableView.mj_header=[MJRefreshNormalHeader  headerWithRefreshingTarget:self refreshingAction:@selector(req)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_header beginRefreshing];
    [self.tableView registerNib:[UINib nibWithNibName:@"Huati_guangchang_xiangqing_tv_cell" bundle:nil] forCellReuseIdentifier:@"Huati_guangchang_xiangqing_tv_cell"];
    
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake( 0, 10,  self.tableView.frame.size.width, self.tableView.frame.size.height - 10);
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"话题java/app/topic/pubTopic" object:nil];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.groupTableViewBackgroundColor;
    [self.tableView.mj_header beginRefreshing];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAction) name:@"话题java/app/topic/pubTopic" object:nil];

    
}
- (void)refreshAction{
    [self.tableView.mj_header beginRefreshing];
}
- (NSMutableArray *)dataArr{
    if(_dataArr == nil)
    {
        _dataArr = [[NSMutableArray alloc] init];
        
    }
    
    return _dataArr;
}


- (void)req{
    
    
    //  请求服务器，获取列表，刷新tv
    self.refreshIndex = 1;
    [self.tableView.mj_footer resetNoMoreData];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:@"1" forKey:@"page"];
    [dict setObject:@"10" forKey:@"pageSize"];
    Huati_guangchang_xiangqing_vc *vc = (Huati_guangchang_xiangqing_vc *)self.parentViewController;
    
    [dict setObject:@(vc.model.ID).stringValue forKey:@"typeId"];
    
    [dict setObject:@(1).stringValue forKey:@"sort"];
    
    [PPHTTPRequest req:@"java/app/topic/getTopicList" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            Topic_getTopicList *model = [Topic_getTopicList mj_objectWithKeyValues:response];
            
            if (!model.data || model.data.count == 0) {
                [self showEmptyViewWithImage:UIImageMake(@"notime_img") text:nil detailText:nil buttonTitle:nil buttonAction:NULL];
            }else{
                [self hideEmptyView];
                self.dataArr = model.data.mutableCopy;
                
                self.totalPage = model.pages;
            }
            
            
            
            
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"] ];
            
        }
        [self endMjRefresh];
        
    } failure:^(NSError *error) {
        [self endMjRefresh];
        
        [QMUITips showError:[error localizedDescription] ];
        
    }];
    
    
}
- (void)loadMoreData{
    self.refreshIndex++;
    
    if (self.refreshIndex > self.totalPage) {
        // 拿到当前的上拉刷新控件，变为没有更多数据的状态
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }else{
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:app_code forKey:@"appCode"];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
        [dict setObject:@(self.refreshIndex).stringValue forKey:@"page"];
        
        
        [dict setObject:@"10" forKey:@"pageSize"];
        Huati_guangchang_xiangqing_vc *vc = (Huati_guangchang_xiangqing_vc *)self.parentViewController;
        
        [dict setObject:@(vc.model.ID).stringValue forKey:@"typeId"];
        [dict setObject:@(1).stringValue forKey:@"sort"];
        
        
        [PPHTTPRequest req:@"java/app/topic/getTopicList" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
                Topic_getTopicList *model = [Topic_getTopicList mj_objectWithKeyValues:response];
                
                if (!model.data) {
                    [self showEmptyViewWithImage:UIImageMake(@"notime_img") text:nil detailText:nil buttonTitle:nil buttonAction:NULL];
                }else{
                    [self hideEmptyView];
                    [self.dataArr addObjectsFromArray:model.data];
                    
                }
                
                
                
                
            }
            else{
                
                
                [QMUITips showError:response[@"error_msg"] ];
                
            }
            [self endMjRefresh];
            
        } failure:^(NSError *error) {
            [self endMjRefresh];
            
            [QMUITips showError:[error localizedDescription] ];
            
        }];
        
    }
    
}
- (void)endMjRefresh{
    
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        [self.tableView reloadData];
    });
    
    if (self.tableView.mj_footer.isRefreshing) {
        [self.tableView.mj_footer endRefreshing];
    }
    
    
    if (self.tableView.mj_header.isRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
    
    
}
#pragma mark - ================== table view data source delegate ==================
/*
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 return self.dataArr.count;
 }
 
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 Huati_guangchang_xiangqing_tv_cell *cell = [tableView dequeueReusableCellWithIdentifier:@"Huati_guangchang_xiangqing_tv_cell"];
 if (!cell) {
 cell = [[Huati_guangchang_xiangqing_tv_cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Huati_guangchang_xiangqing_tv_cell"];
 }
 Topic_getTopicListData *model = self.dataArr[indexPath.row];
 
 //        cell.textLabel.text = list.title;
 //    LzyChangeDetail *m = self.dataArr[ind    exPath.row];
 //    cell.model = m;
 cell.model = model;
 return cell;
 }
 */
- (id<NSCopying>)cachedKeyAtIndexPath:(NSIndexPath *)indexPath {
    Topic_getTopicListData *model = self.dataArr[indexPath.row];
    NSString *cacheKey = @"";
    if (model.recordType == 1) {
        cacheKey = [NSString stringWithFormat:@"%ld,%ld", model.recordType, model.findTopicPageDto.ID];
    }else{
        NSMutableArray *keys = NSMutableArray.new;
        for (Topic_getTopicListAdmanage *ad in model.adManage) {
            [keys addObject:@(ad.ID).stringValue];
        }
        
        cacheKey = [NSString stringWithFormat:@"%ld,%@", model.recordType, [keys componentsJoinedByString:@","]];
    }
    return cacheKey;
}


#pragma mark - <QMUITableViewDelegate, QMUITableViewDataSource>

- (UITableViewCell *)qmui_tableView:(UITableView *)tableView cellWithIdentifier:(NSString *)identifier {
    if ([identifier isEqualToString:kCellIdentifier]) {
        Huati_guangchang_xiangqing_tv_cell *cell = (Huati_guangchang_xiangqing_tv_cell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[Huati_guangchang_xiangqing_tv_cell alloc] initForTableView:tableView withReuseIdentifier:identifier];
        }
        cell.separatorInset = UIEdgeInsetsZero;
        return cell;
    }else if([identifier isEqualToString:k_ad_CellIdentifier]){
        Topic_getTopicList_tv_ad_cell *cell = (Topic_getTopicList_tv_ad_cell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[Topic_getTopicList_tv_ad_cell alloc] initForTableView:tableView withReuseIdentifier:identifier];
        }
        cell.separatorInset = UIEdgeInsetsZero;
        return cell;
    }
    
    
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Topic_getTopicListData *model = self.dataArr[indexPath.row];
    QMUITableViewCell *common_cell;
    if (model.recordType == 1) {
        Huati_guangchang_xiangqing_tv_cell *cell = (Huati_guangchang_xiangqing_tv_cell *)[self qmui_tableView:tableView cellWithIdentifier:kCellIdentifier];
        
        [cell updateCellAppearanceWithIndexPath:indexPath];
        cell.model = model.findTopicPageDto;
        common_cell = cell;
        cell.idxPath = indexPath;
        __weak __typeof(self) weakSelf = self;
        cell.blk = ^(NSIndexPath * _Nonnull idxPath) {
            [weakSelf topicShield:idxPath];
        };
    }else if(model.recordType == 2){
        Topic_getTopicList_tv_ad_cell *cell = (Topic_getTopicList_tv_ad_cell *)[self qmui_tableView:tableView cellWithIdentifier:k_ad_CellIdentifier];
        [cell updateCellAppearanceWithIndexPath:indexPath];
        cell.model = model;
        common_cell = cell;
        cell.idxPath = indexPath;
        __weak __typeof(self) weakSelf = self;
        cell.blk = ^(NSIndexPath * _Nonnull idxPath) {
            [weakSelf adShield:idxPath];
            
        };
    }
    
    
    return common_cell;
}
- (void)topicShield:(NSIndexPath *)indexPath{
    [self.dataArr removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
    
}
- (void)adShield:(NSIndexPath *)indexPath{
    
    [self.dataArr removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    id<NSCopying> cachedKey = [self cachedKeyAtIndexPath:indexPath];
    Topic_getTopicListData *model = self.dataArr[indexPath.row];
    
    CGFloat cellH = 60;
    if (model.recordType == 1) {
        cellH = [tableView qmui_heightForCellWithIdentifier:kCellIdentifier cacheByKey:cachedKey configuration:^(Huati_guangchang_xiangqing_tv_cell *cell) {
            [cell updateCellAppearanceWithIndexPath:indexPath];
            cell.model = model.findTopicPageDto;
        }];
    }else if(model.recordType == 2){
        cellH = 180;
    }
    
    // DLog(@"cachedKey:%@ height:%f",cachedKey, h);
    return cellH;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //     [self.tableView qmui_clearsSelection];
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    Topic_getTopicListData *model = self.dataArr[indexPath.row];
    
    if (model.recordType == 1) {
        Tiezi_xiangqing_vc *vc = [Tiezi_xiangqing_vc new];
        //  列表进入详情，需要列表带一个标志到下一页，然后在下一页请求服务器获取需要的数据
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
        vc.navigationItem.title = @"消息详情";
        vc.hidesBottomBarWhenPushed = YES;
    }else if(model.recordType == 2){
        /* 广告不处理*/
    }
    
    
    
    
}
@end


